package com.wyd.common.util;

import java.util.ArrayList;
import java.util.List;

/**
 * 字符串工具
 * TODO 错误的 不能用
 */
public class OrderedStringUtil {
    private OrderedStringUtil() {
    }
    final static char[] digits = {
            'A' , 'B' ,
            'C' , 'D' , 'E' , 'F' , 'G' , 'H' ,
            'I' , 'J' , 'K' , 'L' , 'M' , 'N' ,
            'O' , 'P' , 'Q' , 'R' , 'S' , 'T' ,
            'U' , 'V' , 'W' , 'X' , 'Y' , 'Z'
    };

    /**
     * 生成一批有序的字符串
     * 65-90(A-Z)选择构造
     */
    public static List<String> getOrderedList(int n) {
        final ArrayList<String> list = new ArrayList<>(n);

        if (n <= 0) {
            return list;
        }

        for (int i = 0; i < n; i++) {
            list.add(toString(i));
        }

        return list;
    }

    public static List<String> getOrderedList2(int n) {
        final ArrayList<String> list = new ArrayList<>(n);

        if (n <= 0) {
            return list;
        }

        char[] chars = {'A'};
        list.add(new String(chars));

        for (int i = 1; i < n; i++) {
            chars = add1(chars);

            list.add(new String(chars));
        }

        return list;
    }

    /**
     * 对字符数组加一
     * A-Z
     */
    private static char[] add1(char[] chars) {
        char[] charArray = chars;
        int index = charArray.length - 1;
        while (true) {
            final char end = charArray[index];

            if (end < 'Z') {
                charArray[index] = (char) (charArray[index] + 1);

                break;
            }

            charArray[index] = 'A';

            index -= 1;
            if (index < 0) {
                final char[] charsNew = new char[charArray.length + 1];
                charsNew[0] = 'A';

                System.arraycopy(charArray, 0, charsNew, 1, charsNew.length - 1);

                charArray = charsNew;
                break;
            }
        }

        return charArray;
    }

    /**
     * 参考的 java.lang.Integer#toString(int, int)
     */
    private static String toString(int i) {
        char[] buf = new char[33];
        int charPos = 32;
        int radix = 26;

        i = -i;

        while (i <= -radix) {
            buf[charPos--] = digits[-(i % radix)];
            i = i / radix;
        }
        buf[charPos] = digits[-i];

        return new String(buf, charPos, (33 - charPos));
    }
}
